package show.me.the.money.service.core;

import java.io.File;
import java.util.HashMap;

import org.dom4j.Document;
import org.dom4j.Element;

import show.me.the.money.accredit.DatabaseUserLoader;
import show.me.the.money.accredit.User;
import show.me.the.money.accredit.UsersController;
import show.me.the.money.servlet.Dispatcher;
import show.me.the.money.util.MD5StringUtil;
import show.me.the.money.util.context.Context;
import show.me.the.money.util.xml.XMLHelper;


public class PasswordChanger implements Service{

	public void execute(HashMap<String,Object> req,HashMap<String,Object> res,Context ctx) {
		String psw = MD5StringUtil.MD5Encode((String) req.get("psw"));
		String newPsw = MD5StringUtil.MD5Encode((String) req.get("newPsw"));
		String msg = "Success";
		int code = 200;
		User user = (User)ctx.get("user.instance");
		long ver = System.currentTimeMillis();
		if(user.validatePassword(psw)){
			String uid = user.getId();
			String filename = UsersController.instance().getConfigFilename(uid);
			if(filename != null){
				File f = new File(filename);
				Document doc = UsersController.instance().getConfigDoc(uid);
				Element define = doc.getRootElement();
				define.addAttribute("password", newPsw);
				define.addAttribute("version", String.valueOf(ver));
				XMLHelper.putDocument(f, doc);
				f.setLastModified(ver);
				UsersController.instance().clear(uid);
			}else{
				boolean flag = DatabaseUserLoader.resetPassword(uid, newPsw,String.valueOf(ver));
				if(flag){
					Document doc = DatabaseUserLoader.getUserDoc(uid);
					UsersController.instance().uploadUser(doc, uid);
				}else{
					code = 500;
					msg = "OperatorFailed";
				}
			}
			UsersController.instance().reload(uid);
		}else{
			code = 501;
			msg = "Wrong password";
		}
		Dispatcher.setResInfo(res, code, msg);
	}
}
